import Taro from "@tarojs/taro";
import React, { useState, useEffect } from "react";
import { View, Picker } from "@tarojs/components";
import { AtForm, AtInput, AtButton, AtList, AtListItem, AtTextarea, AtImagePicker, AtToast, AtMessage } from 'taro-ui';
import { addArticle, getAllCategory, addImage } from './api';
import "taro-ui/dist/style/components/form.scss";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/image-picker.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/message.scss";
import css from "./index.module.less";

export default function Index() {
  const host = 'http://8.130.123.79:8090';
  const [allCategory, setAllCategory] = useState([]);
  const [title, setTitle] = useState("");
  const [sortTitle, setSortTitle] = useState("");
  const [content, setContent] = useState("");
  const [images, setImages] = useState([]);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    getAllCategory().then((res) => {
      if (res.code === 200) {
        const data = res.data;
        let categoryData = [];
        for (const category of data) {
          categoryData.push(category.title);
        }
        setSortTitle(categoryData[0])
        setAllCategory(categoryData);
      }
    })
  }, [])

  const handleChangeTitle = (v) => {
    setTitle(v)
    console.log(v);
  }

  const onChangeSort = (e) => {
    let index = e.detail.value;
    setSortTitle(allCategory[index]);
  }

  const onChangeContent = (e) => {
    setContent(e);
  }

  const onChangeImages = (e) => {
    setImages(e);
  }

  // 上传多文件
  const uploadFiles = (uuid, files) => {
    for (let i = 0; i < files.length; i++) {
      const element = files[i];
      Taro.uploadFile({
        url: host + '/attachment/upload',
        filePath: element.url,
        name: 'files',
        formData: images,
        success (res) {
          const data = JSON.parse(res.data);
          const url = data.data[0];
          console.log(res.data);
          addImage({
            articleId: uuid,
            url: url
          }).then((r) => {

          });
        }
      })
    }
  }

  const onSubmit = () => {
    Taro.getStorage({
      key: 'userInfo',
      success: function (res) {
        const userInfo = res.data;
        console.log(userInfo);
        const data = {
          article : {
              author: userInfo.username,
              authorId: userInfo.id,
              commentId: 0,
              content: content,
              likes: 0,
              status: 0,
              title: title,
          },
          title: sortTitle
        }
        if(userInfo.status === 0) {
          Taro.atMessage({
            'message': "用户已被冻结，请联系管理员",
            'type': "error",
            'duration': 3000
          })
        } else
        {
          if (title.length === 0) {
            Taro.atMessage({
              'message': "请输入标题内容",
              'type': "warning",
              'duration': 1000
            })
          } else if (content.length === 0) {
            Taro.atMessage({
              'message': "请输入文章内容",
              'type': "warning",
              'duration': 1000
            })
          } else if (images.length === 0) {
            Taro.atMessage({
              'message': "请至少上传一张图片",
              'type': "warning",
              'duration': 1000
            })
          } else {
            addArticle(data).then((res) => {
              if (res.code === 200) {
                let uuid = res.data;
                uploadFiles(uuid, images);
                setOpen(true);
              } else {
                Taro.atMessage({
                  'message': res.msg,
                  'type': "error",
                  'duration': 3000
                })
              }
            });
          }
        }

        // addArticle(data).then((res) => {
        //   if (res.code === 200) {
        //     let uuid = res.data;
        //     uploadFiles(uuid, images);
        //     setOpen(true);
        //   } else {

        //   }
        // });
      }
    })

    console.log("submit");
    console.log(title, sortTitle);

  }

  const onReset = () => {
    setTitle("");
    setContent("");
    setImages([]);
  }
  return (
    <View>
      <AtMessage />
      <AtToast isOpened={open} text={open? "新增文章成功" : "新增文章失败"} icon="{icon}"></AtToast>
      <AtForm
      >
        <AtInput
          name='value'
          title='标题'
          type='text'
          placeholder='请输入文章标题'
          value={title}
          onChange={handleChangeTitle}
        />
        {allCategory.map((category) => {
          return (
            <View key={category.id}>
              {category.title}
            </View>
          )
        })}
        <Picker mode='selector' range={allCategory} onChange={onChangeSort}>
          <AtList>
            <AtListItem
              title='分类'
              extraText={sortTitle}
            />
          </AtList>
        </Picker>
        <AtTextarea
          value={content}
          onChange={onChangeContent}
          maxLength={200}
          placeholder='请输入内容......'
        />
        <AtImagePicker
          files={images}
          onChange={onChangeImages}
        />
        <AtButton type='primary' onClick={onSubmit}>提交</AtButton>
        <AtButton onClick={onReset}>重置</AtButton>
      </AtForm>
    </View>
  );
}
